package com.jetpackframework.retrofit.converter;

import androidx.annotation.Nullable;

import com.gwm.annotation.http.HTTP;
import com.jetpackframework.retrofit.Converter;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import okhttp3.Request;
import okhttp3.RequestBody;

public class RequestBodyRequestConverter extends HttpRequestConverter<Request> {
    private static Converter converter;
    public static synchronized Converter get(){
        if (converter == null){
            converter = new RequestBodyRequestConverter();
        }
        return converter;
    }
    private RequestBodyRequestConverter(){}
    @Nullable
    @Override
    public Request convert(Method method,Object[] args){
        HTTP annotation = method.getAnnotation(HTTP.class);
        Request.Builder builder = new Request.Builder();
        RequestBody body = null;
        initHttpBasicInfo(method,args,builder);
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < annotations.length; i++) {     //i:第几个参数的注解
            if (annotations[i].length > 0) {
                for (int j = 0; j < annotations[i].length; j++) {  //j: 第i个参数上的第j个注解
                    if (annotations[i][j] instanceof com.gwm.annotation.http.RequestBody){
                        body = (RequestBody) args[i];
                    }
                }
            }
        }
        if (annotation.way() == HTTP.WAY.DELETE){
            builder = builder.delete(body);
        }else if (annotation.way() == HTTP.WAY.POST){
            builder = builder.post(body);
        }else if (annotation.way() == HTTP.WAY.PUT){
            builder = builder.put(body);
        }
        return builder.build();
    }
}
